package top.huhuiyu.springboot3.p2301.service.api.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot3.p2301.entity.api.InfoData;
import top.huhuiyu.springboot3.p2301.service.api.InfoService;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class InfoServiceImpl implements InfoService {
    private final RestTemplate restTemplate;

    @Override
    public List<InfoData> queryInfo(Integer page) {
        List<InfoData> list = new ArrayList<>();
        String url = BASE_URL;
        if (page > 1) {
            url += "_" + page;
        }
        String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
        // 将网站的html转为Document对象
        Document document = Jsoup.parse(result);
        // 找到class为sub-page-list的ul元素中所有的li元素(就是js中的css选择器查询元素)
        document.select("ul.sub-page-list li").forEach(li -> {
            log.debug("li:{}", li);
            InfoData info = new InfoData();
            // 获取基本信息,标题和链接是a标记
            Element link = li.select("a").first();
            info.setTitle(link.text());
            info.setUrl(link.attr("href"));
            // 发布时间在span标记中
            info.setPostTime(li.select("span").text());
            // 获取详情信息（需要通过url对应的页面获取）
            queryInfoDetail(info);
            list.add(info);
        });
        return list;
    }

    private void queryInfoDetail(InfoData info) {
        String result = restTemplate.getForObject(info.getUrl(), String.class);
        Document document = Jsoup.parse(result);
        List<Element> tds = document.select("div.sub-page-content table.tableBox td").stream().toList();
        info.setF1(tds.get(1).text());
        info.setF2(tds.get(3).text());
        info.setF3(tds.get(5).text());
        info.setF4(tds.get(7).text());
        info.setF5(tds.get(9).text());
        info.setF6(tds.get(11).text());
        info.setF7(tds.get(13).text());
        info.setF8(tds.get(17).text());
        info.setF9(tds.get(19).text());
        info.setF10(tds.get(21).text());
        info.setF11(tds.get(23).text());
    }

    @Override
    public void queryInfoToExcel(String path) throws Exception {
        // 创建excel工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建汉寿数据表
        HSSFSheet sheet = workbook.createSheet("汉寿数据");
        // 创建表头
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("项目名称");
        row.createCell(1).setCellValue("项目编号");
        row.createCell(2).setCellValue("交易方式");
        row.createCell(3).setCellValue("面积/数量");
        row.createCell(4).setCellValue("项目底价");
        row.createCell(5).setCellValue("成交价格");
        row.createCell(6).setCellValue("成交时间");
        row.createCell(7).setCellValue("转出方");
        row.createCell(8).setCellValue("成交方");
        row.createCell(9).setCellValue("转出期限");
        row.createCell(10).setCellValue("标的区域");
        // 循环输出数据
        int rowNum = 1;
        for (int i = 1; i <= 2; i++) {
            List<InfoData> list = queryInfo(i);
            for (InfoData info : list) {
                row = sheet.createRow(rowNum);
                row.createCell(0).setCellValue(info.getF1());
                row.createCell(1).setCellValue(info.getF2());
                row.createCell(2).setCellValue(info.getF3());
                row.createCell(3).setCellValue(info.getF4());
                row.createCell(4).setCellValue(info.getF5());
                row.createCell(5).setCellValue(info.getF6());
                row.createCell(6).setCellValue(info.getF7());
                row.createCell(7).setCellValue(info.getF8());
                row.createCell(8).setCellValue(info.getF9());
                row.createCell(9).setCellValue(info.getF10());
                row.createCell(10).setCellValue(info.getF11());
                rowNum++;
            }
        }
        // 将列宽调整为自适应宽度
        for (int i = 0; i < 11; i++) {
            sheet.autoSizeColumn(i);
        }
        // 输出到文件
        try (FileOutputStream fos = new FileOutputStream(path)) {
            workbook.write(fos);
            workbook.close();
        }
    }
}
